//
//  WmcUserdefault.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/5/9.
//

import UIKit

extension WmcUserdefault.Key {
    /// 提示记录
    struct Tips {}

    /// 弹窗记录
    struct Alert {}

    /// 状态记录
    struct State {}

    /// 数据记录
    struct Data {}
}

extension WmcUserdefault.Key {
    /// 网络日志开关
    static let networkLogSwitch: WmcUserdefault.Key = .init("network_log_switch")

    /// 网络环境
    static let networkEnvironment: WmcUserdefault.Key = .init("network_environment")
}

// MARK: - [WmcUserdefault]

class WmcUserdefault: WmcBaseView {
    /// 存储键值
    struct Key: Hashable, Equatable, RawRepresentable {
        // Lifecycle

        public init(rawValue: String) {
            self.rawValue = rawValue
        }

        /// 创建一个存储键值
        /// - Parameters:
        ///   - rawValue: 表名键值字符串
        public init(_ rawValue: String, bindUser: Bool = false) {
            self.init(rawValue: rawValue)
            self.isBindUser = bindUser
        }

        // Public

        /// 值
        public var rawValue: String

        public var isBindUser: Bool = false
    }

    // Internal

    /// 存储
    static func save(value: Any, forKey: Key, associateValue: String? = nil) {
        var key = forKey.rawValue
        if let associateValue = associateValue {
            key = "\(key).\(associateValue)"
        }
        if forKey.isBindUser { // 如果需要绑定userId
            if let id = WmcLoginManager.shared.wmcAccountModel?.memberId {
                key.append(".memberId=\(id)")
            }
        }

        UserDefaults.standard.set(value, forKey: key)
        UserDefaults.standard.synchronize()
    }

    /// 取
    static func object<T>(forKey: Key, associateValue: String? = nil) -> T? {
        var key = forKey.rawValue
        if let associateValue = associateValue {
            key = "\(key).\(associateValue)"
        }
        if forKey.isBindUser {
            if let id = WmcLoginManager.shared.wmcAccountModel?.memberId {
                key.append(".memberId=\(id)")
            }
        }

        let value = UserDefaults.standard.object(forKey: key)
        UserDefaults.standard.synchronize()
        guard let newValue = value as? T else { return nil }
        return newValue
    }
    
    /// 删除
    static func remove(forKey: Key, associateValue: String? = nil) {
        var key = forKey.rawValue
        if let associateValue = associateValue {
            key = "\(key).\(associateValue)"
        }
        if forKey.isBindUser {
            if let id = WmcLoginManager.shared.wmcAccountModel?.memberId {
                key.append(".memberId=\(id)")
            }
        }
        UserDefaults.standard.removeObject(forKey: key)
        UserDefaults.standard.synchronize()
    }
}
